from maix import GPIO
from machine import UART
import sensor, image, time, lcd
from fpioa_manager import fm

# 注册IO：KEY-->IO16
fm.register(16, fm.fpioa.GPIO1)
KEY = GPIO(GPIO.GPIO1, GPIO.IN)

# 映射串口引脚
fm.register(6, fm.fpioa.UART1_RX, force=True)
fm.register(7, fm.fpioa.UART1_TX, force=True)


# 初始化串口
uart = UART(UART.UART1, 115200, read_buf_len=4096)


# LCD初始化
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
sensor.set_vflip(1)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
clock = time.clock()



# 条形码类型
def barcode_name(code):
    if(code.type() == image.EAN2):
        return "EAN2"
    if(code.type() == image.EAN5):
        return "EAN5"
    if(code.type() == image.EAN8):
        return "EAN8"
    if(code.type() == image.UPCE):
        return "UPCE"
    if(code.type() == image.ISBN10):
        return "ISBN10"
    if(code.type() == image.UPCA):
        return "UPCA"
    if(code.type() == image.EAN13):
        return "EAN13"
    if(code.type() == image.ISBN13):
        return "ISBN13"
    if(code.type() == image.I25):
        return "I25"
    if(code.type() == image.DATABAR):
        return "DATABAR"
    if(code.type() == image.DATABAR_EXP):
        return "DATABAR_EXP"
    if(code.type() == image.CODABAR):
        return "CODABAR"
    if(code.type() == image.CODE39):
        return "CODE39"
    if(code.type() == image.PDF417):
        return "PDF417"
    if(code.type() == image.CODE93):
        return "CODE93"
    if(code.type() == image.CODE128):
        return "CODE128"


#主循环
while True:
    clock.tick()
    img = sensor.snapshot()               # 拍摄
    codes = img.find_barcodes()           # 找条形码

    if codes:                             # 如果找到任何条形码
        for code in codes:                # 绘制矩形框并显示其信息在屏幕上
            img.draw_rectangle(code.rect())
            img.draw_string(2, 2, barcode_name(code) + ": " + code.payload(), color=(255, 255, 255), scale=2)

########################################### 按键判断
    if not KEY.value():
        while not KEY.value():
            pass

########################################### 按键按下打印和发送串口数据
        if codes:
            for code in codes:
                payload = code.payload()
                fps = clock.fps()
                print((payload))
                uart.write(payload.encode())

    lcd.display(img)                      # LCD显示
